﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Converters;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System;

namespace Converter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void ButtonConvert_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Input.Text)) return;
            if (Input.Text != null)
            {
                Converted.Clear();
                double input = double.Parse(Input.Text);
                byte[] result = CalCodeFromTemp(input);
                var hexString = BitConverter.ToString(result).Replace("-", "");
                Converted.Text = hexString;
            }
        }
        public static byte[] CalCodeFromTemp(double CurrentTemp)
        {
            // 1. 计算Rt（解方程：Rt = 100 * (1 + 0.0039083 * T - 0.0000005775 * T^2)）
            double Rt = 100 * (1 + 0.0039083 * CurrentTemp - 0.0000005775 * CurrentTemp * CurrentTemp);

            // 2. 计算Vtemp（解方程：Vtemp = 2500 * Rt / (4990 + Rt) - 2500.0 / 5090 * 100）
            double Vtemp = 2500 * Rt / (4990 + Rt) - 2500.0 / 5090 * 100;

            // 3. 计算VCode（VCode = Vtemp * 16777215 / 4096）
            int VCode = (int)(Vtemp * 16777215 / 4096);

            // 4. 转换为字节数组并移除最后一个字节
            byte[] bytes = BitConverter.GetBytes(VCode);
            Array.Resize(ref bytes, 3); // 保留前3个字节，等同于移除最后一个字节

            return bytes;
        }

        private void ButtonConvertReverse_Click(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty(Converted.Text)) return;
            try
            {
                // 1. 移除所有空格并转为大写
                string hexText = Converted.Text.Replace(" ", "").ToUpper();

                // 2. 检查是否为有效的16进制字符串
                if (hexText.Length % 2 != 0)
                {
                    MessageBox.Show("16进制字符串长度必须为偶数", "格式错误");
                    return;
                }

                // 3. 将16进制字符串转换为字节数组
                byte[] byteArray = new byte[hexText.Length / 2];
                for (int i = 0; i < hexText.Length; i += 2)
                {
                    byteArray[i / 2] = Convert.ToByte(hexText.Substring(i, 2), 16);
                }

                // 4. 调用温度计算函数
                double temperature = CalTempFromCode(byteArray);

                // 5. 显示结果
                Input.Clear();
                Input.Text = temperature.ToString(); // 显示两位小数("F2")
            }
            catch (Exception ex)
            {
                MessageBox.Show($"转换失败: {ex.Message}", "错误");
            }
        }
        public static double CalTempFromCode(byte[] TempCode)
        {
            var Codes = new List<byte>(TempCode);
            Codes.Add(0);
            var VCode = BitConverter.ToInt32(Codes.ToArray(), 0);
            var Vtemp = VCode / (16777215.0 / 4096.0);
            var Rt =
                ((2500.0 / 5090.0 * 100.0 + Vtemp) * 4990.0)
                / (2500.0 - (Vtemp + 2500.0 / 5090.0 * 100.0));
            // aX^2 + b x + c = 0
            var a = Math.Round(100.0 * 0.0000005775, 8);
            var b = -100.0 * 0.0039083;
            var c = Rt - 100.0;
            double S = Math.Round(b * b - 4 * a * c, 10),
                x1,
                x2,
                CurrentTemp = 0.0;
            if (S < 0)
            {
                CurrentTemp = double.NaN;
            }
            else if (S > 0)
            {
                x1 = (-b - Math.Sqrt(S)) / (2.0 * a);
                x2 = (-b + Math.Sqrt(S)) / (2.0 * a);
                CurrentTemp = Math.Round(x1, 4);
            }
            else
            {
                x1 = x2 = (-b) / (2 * a);
                CurrentTemp = Math.Round(x1, 2);
            }
            return CurrentTemp;
        }
    }
}